<template>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :http-request="upload"

      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
  export default {
    props:{
      imageUrl:{
        type:String,
        default:''
      }
    },
    data() {
      return {
      };
    },
    methods: {
      // handleAvatarSuccess(file) {
      //   let reader = new FileReader()
      //   reader.readAsDataURL(file.raw)
      //   // reader 读取文件成功的回调
      //   reader.onload = (e)=>{
      //     this.$emit('update:imageUrl',reader.result)
      //   }

      //   // this.imageUrl = URL.createObjectURL(file.raw);
      // },
      beforeAvatarUpload(file) {
        // 判断文件类型
        const isJPG = ['image/jpeg','image/png','image/gif','image/bmp'].includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      // 自定义上传
      upload(file) {
        // 将file文件转为dataURL
        // let reader = new FileReader()
        // reader.readAsDataURL(file.file)
        // // reader 读取文件成功的回调
        // reader.onload = (e)=>{
        //   this.$emit('update:imageUrl',reader.result)
        // }



        // // 初始化COS
        const cos=new COS({
          // 应用标识
          SecretId:'AKIDwDctz99DIWaXO7kCXikcIn5A9Ie0LXaI',
          // 应用密钥
          SecretKey:'Pp5GRUOWzOl4DsZI1gGh4jTG5nL8ynX6'
        })

        // 进行上传
        cos.putObject({
          // 存储桶名称
          Bucket:'wangxuesong-1322754383',
          // 存储桶地域
          Region:'ap-nanjing',
          // 文件名称
          Key:file.file.name,
          StorageClass:'STANDARD',
          // 文件对象
          Body:file.file
        },(err,data)=>{
          console.log(data);
          // 标识腾讯云成功返回地址
          if(data.statusCode==200&&data.Location)
          {
            this.$emit('update:imageUrl','http://'+data.Location)
          }
          else {
            this.$message.error(err.Message)
          }
        })

      }
    }
  }
</script>

<style lang="scss" >
 .avatar-uploader .el-upload  {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>